<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span style="font-size: medium">{{ $t('company.companyDetail') }}</span>
        </div>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="companyForm"
        :rules="companyRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        style="padding-top: 10px"
        :disabled="disabled"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('company.userAccount')" prop="userName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="companyForm.userName"
                :placeholder="$t('company.iptUserAccount')"
                :disabled="readonly"
                maxlength="25"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.userPwd')"
              prop="password"
              v-if="!readonly"
              class="requireLabel"
            >
              <el-input
                class="required_input"
                v-model="companyForm.password"
                :placeholder="$t('company.iptUserPwd')"
                type="password"
                autocomplete="off"
                :show-password="true"
              />
            </el-form-item>
            <el-form-item :label="$t('company.licenseNo')" prop="licenseNo" class="requireLabel">
              <el-input
                class="required_input"
                v-model="companyForm.licenseNo"
                :placeholder="$t('company.inputOrderNo')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('company.useTimeLimit')" prop="timeLimit" class="requireLabel">
              <el-date-picker
                :disabled="!superAdmin"
                v-model="companyForm.timeLimit"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="position: relative; left: 10px"
                type="date"
                :clearable="false"
                :placeholder="$t('company.useTimeLimitTip')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.accountLimit')"
              prop="accountLimit"
              class="requireLabel"
            >
              <el-input
                class="required_input"
                v-model="companyForm.accountLimit"
                :disabled="!superAdmin"
                :placeholder="$t('company.accountLimitTip')"
                maxlength="5"
              />
            </el-form-item>
            <el-form-item :label="$t('company.webSite')" prop="webSite" class="normal_label">
              <el-input
                v-model="companyForm.webSite"
                :placeholder="$t('company.webSite')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('company.phone')" class="normal_label" prop="telNo">
              <el-input
                v-model="companyForm.telNo"
                :placeholder="$t('company.iptPhone')"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="Email" prop="email" class="normal_label">
              <el-input
                v-model="companyForm.email"
                placeholder="Email"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('company.companyNameCn')" prop="name" class="requireLabel">
              <el-input
                class="required_input"
                v-model="companyForm.name"
                :placeholder="$t('company.inputCompany')"
                maxlength="50"
                show-word-limit
                @blur="genPinyin(1, $event)"
              />
            </el-form-item>
            <el-form-item :label="$t('company.companyNameEn')" prop="enName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="companyForm.enName"
                :placeholder="$t('company.companyNameEnTip')"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.companyNameAddressCn')"
              prop="address"
              class="normal_label"
            >
              <el-input
                v-model="companyForm.address"
                :placeholder="$t('company.addresInfoCn')"
                type="textarea"
                maxlength="255"
                show-word-limit
                :autosize="{ minRows: 2 }"
                @blur="genPinyin(2, $event)"
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.companyNameAddressEn')"
              prop="enAddr"
              class="normal_label"
            >
              <el-input
                v-model="companyForm.enAddr"
                :placeholder="$t('company.iptAddressEn')"
                type="textarea"
                show-word-limit
                :autosize="{ minRows: 2 }"
                maxlength="255"
              />
            </el-form-item>
            <el-form-item :label="$t('company.uploadLogo')" class="normal_label">
              <el-upload
                class="avatar-uploader"
                accept=".jpeg,.png,.jpg,.bmp,.gif"
                :action="uploadUrl"
                :show-file-list="false"
                :multiple="false"
                :on-success="afterUpload"
                :headers="headers"
                :disabled="disabled"
              >
                <img v-if="companyForm.url" :src="getLogoUrl()" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row class="detailFooter">
        <el-col v-if="disabled">
          <el-button type="primary" @click="goBack">{{ $t('common.back') }}</el-button>
        </el-col>
        <el-col v-else>
          <el-button type="primary" :loading="loading" @click="saveCompany" plain>{{
            $t('common.save')
          }}</el-button>
          <el-button type="info" @click="goBack" plain>{{ $t('common.giveUp') }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts">
import { onActivated, onMounted, reactive, toRefs, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { PATH_URL } from '@/config/axios'
import { getCurUser, getMd5Password, getToken } from '@/utils'
import { registerCompany, companyDetail, updateCompany } from '@/api/company'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useCache } from '@/hooks/web/useCache'
import { useI18n } from '@/hooks/web/useI18n'
import { getPinyin } from '@/api/common'
export default {
  name: 'EditCompany',
  components: { Plus },
  props: {},
  setup() {
    const { currentRoute } = useRouter()
    const { wsCache } = useCache()
    const ruleFormRef = ref()
    const { emitter } = useEmitt()
    const { t } = useI18n()
    const state = reactive({
      superAdmin: false,
      // 基本資料
      companyForm: {
        tenantId: '',
        userName: '',
        password: '',
        licenseNo: '',
        timeLimit: '',
        telNo: '',
        email: '',
        webSite: '',
        accountLimit: '',
        name: '',
        enName: '',
        address: '',
        enAddr: '',
        url: ''
      },
      //剩下的不是必填的
      companyRules: {
        userName: {
          required: true,
          pattern:
            /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{2,25}$/,
          message: t('company.iptUserNameNo'),
          trigger: ['blur', 'change']
        },
        password: {
          required: true,
          pattern:
            /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{6,25}$/,
          message: t('login.errPasswordFormat'),
          trigger: ['blur', 'change']
        },
        licenseNo: {
          required: true,
          message: t('company.licenseNumberNo'),
          trigger: ['blur', 'change']
        },
        telNo: [
          {
            pattern: /^(\(){0,1}(\+){0,1}[\d\-( )]+$/,
            message: t('company.errMobileOrTelNo'),
            trigger: ['blur', 'change']
          },
          {
            pattern: '[^ \x22]+',
            message: t('company.emptyMsg'),
            trigger: ['blur', 'change']
          }
        ],
        email: {
          pattern: /^[^@]+[@]{1}[^@]+$/,
          message: 'Email' + t('company.errFormat'),
          trigger: 'blur'
        },
        timeLimit: [{ required: true, message: t('company.useTimeLimitTip'), trigger: 'blur' }],
        accountLimit: {
          required: true,
          message: t('company.accountLimitTip'),
          trigger: ['blur', 'change']
        },
        name: { required: true, message: t('company.errNameCnEmpty'), trigger: 'blur' },
        enName: [
          { required: true, message: t('company.errNameEnEmpty'), trigger: 'blur' },
          {
            pattern: /^[^\u4e00-\u9fa5]+$/,
            message: t('common.errNotCN'),
            trigger: ['blur', 'change']
          }
        ],
        enAddr: {
          pattern: /^[^\u4e00-\u9fa5]+$/,
          message: t('common.errNotCN'),
          trigger: ['blur', 'change']
        }
      },
      loading: false,
      disabled: false,
      readonly: false
    })
    onMounted(async () => {
      init()
    })
    onActivated(async () => {})
    const methods = {
      initData() {
        state.companyForm = {
          tenantId: '',
          userName: '',
          password: '',
          licenseNo: '',
          timeLimit: '',
          telNo: '',
          email: '',
          webSite: '',
          accountLimit: '',
          name: '',
          enName: '',
          address: '',
          enAddr: '',
          url: ''
        }
      },
      // 保存
      saveCompany() {
        ruleFormRef.value.validate(async (vaild) => {
          if (vaild) {
            state.loading = true
            let params = Object.assign({}, state.companyForm)
            if (state.companyForm.tenantId != '') {
              // 修改
              await updateCompany(params)
                .then((res) => {
                  if (res) {
                    emitter.emit('refreshCompanyList')
                    methods.goBack()
                  }
                  state.loading = false
                })
                .catch(() => {
                  state.loading = false
                })
            } else {
              //新增
              params.password = getMd5Password(state.companyForm.password)
              await registerCompany(params)
                .then((res) => {
                  if (res) {
                    methods.goBack()
                    emitter.emit('refreshCompanyList')
                  }
                  state.loading = false
                })
                .catch(() => {
                  state.loading = false
                })
            }
          }
        })
      },
      // 返回
      goBack() {
        emitter.emit('closeTag', {
          closePath: currentRoute.value.fullPath,
          backPath: '/Company/CompanyManagement'
        })
      },
      //上传LOGO后事件
      afterUpload(result) {
        if (!result.success) {
          return
        }
        const data = result.data[0]
        //将返回的文件ID转成JSON格式保存在对应的字段中
        let url = { fileId: data.pkId, createBy: data.remark }
        state.companyForm.url = JSON.stringify(url)
      },
      getLogoUrl() {
        let url = PATH_URL + 'form/file/previewFile?isScale=true'
        const fileObj = JSON.parse(state.companyForm.url)
        url += '&fileId=' + fileObj.fileId
        url += '&time=' + new Date().getTime()
        url += '&token=' + getToken()
        return url
      },
      async genPinyin(type, event) {
        const text = event.target.value
        if (!text || text.length == 0) {
          return
        }
        if (type == 1 && state.companyForm.enName.length > 0) {
          return
        }
        if (type == 2 && state.companyForm.enAddr.length > 0) {
          return
        }
        let data = (await getPinyin(text, 50)) as any
        if (type == 1) {
          state.companyForm.enName = data.data
        } else if (type == 2) {
          state.companyForm.enAddr = data.data
        }
      }
    }
    useEmitt({
      name: 'editCompany',
      callback: (type: String) => {
        if (type == 'edit' || type == 'look') {
          init()
        } else if (type == 'add') {
          // console.log('add')
          ruleFormRef.value.resetFields()
          state.readonly = false
          methods.initData()
        }
      }
    })
    //渲染页面的接口
    const init = async () => {
      // 獲取當前用戶的類型
      state.superAdmin = getCurUser().superAdmin
      if (wsCache.get('companyStatus') != null) {
        if (wsCache.get('companyStatus') == 'look') state.disabled = true
        state.readonly = true
        const res = await companyDetail({ tenantId: wsCache.get('companyId') })
        state.companyForm = res.data
        // 清空表單驗證信息
        setTimeout(() => {
          ruleFormRef.value.clearValidate()
        }, 50)
      }
    }
    return {
      ...toRefs(state),
      ruleFormRef,
      ...methods
    }
  },
  data() {
    return {
      uploadUrl: PATH_URL + 'form/file/upload'
    }
  },
  computed: {
    headers() {
      let token = getToken()
      if (token) {
        return { Authorization: token }
      }
      return {}
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  padding: 0 50px;

  .card-header {
    font-size: 22px;
    font-weight: 700;
  }

  :deep(.el-input) {
    font-size: 12px;
  }

  :deep(.el-textarea__inner) {
    height: 80px;
    font-size: 12px;
  }

  :deep(.el-input__inner) {
    &::placeholder {
      font-size: 12px;
    }
  }

  .el-select-dropdown__item {
    font-size: 12px;
  }

  .avatar-uploader {
    width: 82px;
    height: 82px;
    display: block;
    position: relative;
    border: 1px dashed #cdd0d4;

    .el-icon.avatar-uploader-icon {
      width: 50px;
      height: 50px;
      font-size: 30px;
      position: absolute;
      left: 20%;
      top: 18%;
      color: #8c939d;
    }
  }

  .avatar-uploader:hover {
    border-color: #409eff;
  }
}

.el-col .el-button {
  margin: 0 30px;
}

.normal_label,
.required_input {
  position: relative;
  left: 10px;
}

:deep(.normal_label .el-form-item__error) {
  left: 0px;
}

:deep(.requireLabel .el-form-item__error) {
  margin-left: 10px;
}

// 查詢狀態下一般input輸入框已填信息變黑色展示
:deep(.el-input.is-disabled .el-input__inner) {
  color: #000000;
}

// 查詢狀態下textarea輸入框已填信息變黑色展示
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #000000;
}

// 查詢狀態下一般input輸入框placeholder隱藏
:deep(.el-input.is-disabled .el-input__inner) {
  &::placeholder {
    color: transparent;
  }
}
// 查詢狀態下textarea輸入框placeholder隱藏
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  &::placeholder {
    color: transparent;
  }
}
</style>
